package com.dataporter.gather.web;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dataporter.gather.patient.Patient;
import com.dataporter.gather.patient.PatientService;
import com.touchwisdom.modular.util.config.Page;

@Controller
@RequestMapping("/patient")
public class PatientController {
	@Resource
	private PatientService patientService;

	@RequestMapping("/index.action")
	public String index() {
		return "patient/index";
	}

	@ResponseBody
	@RequestMapping("/list.action")
	public String list(EasyUiPage<Patient> easyuiPage) {
		Page<Patient> page = this.patientService.findByPage(easyuiPage);
		StringBuilder builder = new StringBuilder("{\"total\":\"");
		builder.append(page.getTotalCount());
		builder.append("\",\"rows\":[");
		Date date = null;
		for (Patient patient : page.getResult()) {
			builder.append("{\"id\":\"").append(patient.getId());
			builder.append("\",\"name\":\"").append(patient.getName());
			builder.append("\",\"sex\":\"").append(patient.getSex());
			date = patient.getStartTime();
			builder.append("\",\"startTime\":\"");
			if (date != null) {
				builder.append(DateFormatUtils.format(date, "yyyy-MM-dd"));
			}
			date = patient.getEndTime();
			builder.append("\",\"endTime\":\"");
			if (date != null) {
				builder.append(DateFormatUtils.format(date, "yyyy-MM-dd"));
			}
			builder.append("\",\"doctor\":\"").append(patient.getDoctor());
			builder.append("\",\"nurse\":\"").append(patient.getNurse());
			builder.append("\",\"age\":\"").append(patient.getAge());
			builder.append("\",\"equipNo\":\"").append(patient.getEquipNo())
					.append("\"},");
		}
		builder.deleteCharAt(builder.length() - 1);
		builder.append("]}");

		return builder.toString();
	}

	@ResponseBody
	@RequestMapping("/save.action")
	public String save(Patient patient) {
		this.patientService.saveEntity(patient);
		return Boolean.TRUE.toString().toLowerCase();
	}

	@ResponseBody
	@RequestMapping("/update.action")
	public String update(Patient patient) {
		this.patientService.saveEntity(patient);
		return Boolean.TRUE.toString().toLowerCase();
	}

	@ResponseBody
	@RequestMapping("/delete.action")
	public String delete(Patient patient) {
		this.patientService.deleteEntity(patient);
		return new EasyUiMessage().toString();
	}
}